<template>
	<view class="rocker-qrcode-app">
		<view class="scan-container" @click="scanItem" v-if="state==0">
			<view class="is-not-vip-user" v-if="!isVipUser">当前功能仅对会员开放</view>
			<view class="image" v-if="isVipUser">
				<image src="../../../static/scan.png" style="width:400upx;height:400upx;"></image>
			</view>
			<view class="btn btn-primary btn-scan" v-if="isVipUser">点击扫描储物柜上的二维码</view>
		</view>
		<view class="rent" v-if="state==1">
			<view class="head">租用设备</view>
			<view class="fields">
				<view class="field">
					<view class="title">设备编号:</view>
					<view class="value">{{machineNO}}</view>
				</view>
				<view class="field">
					<view class="title">费用:</view>
					<view class="value">一个月以内免费，超过0.1元/天</view>
				</view>
<!--				<view class="field">
					<view class="title">每小时费用(元):</view>
					<view class="value">{{teaConfig.lockerPrice}}</view>
				</view>-->
				<view class="field" style="display: none">
					<view class="title">结束时间:</view>
					<view class="value">
						<DatePicke
						   startYear="2019"
						   endYear="2030"
						   :val="selectedTime"
						   @confirm="onDateConfirm"
						   ref="DatePicker"></DatePicke>
						<view @click="datePicker">
							<text v-if="!selectedTime">请选择时间</text>
							<text v-if="selectedTime">{{selectedTime}}</text>
						</view>

						<!--
						<picker style="width:100%;" @change="bindPickerChange('hour', 'hourArray', $event)" :value="item.hour" :range="hourArray" range-key="value">
						    <view class="uni-input">{{item.hour?item.hour: '请选择'}}</view>
						</picker>
						-->
					</view>
				</view>
				<view class="field" style="display: none">
					<view class="title">租用小时:</view>
					<view class="value">
						{{item.hour}}
					</view>
				</view>
			</view>
			<view class="btn btn-primary btn-pay" @click="rentItem">确定租用</view>
		</view>
		<view class="rent" v-if="state==2">
			<view class="head">当前租用设备</view>
			<view class="fields">
				<view class="field">
					<view class="title">备注:</view>
					<view class="value">{{rentInfo.remark}}</view>
				</view>
				<view class="field">
					<view class="title">格子编号:</view>
					<view class="value">{{rentInfo.channel}}</view>
				</view>
				<view class="field">
					<view class="title">开始时间:</view>
					<view class="value">{{rentInfo.startDt}}</view>
				</view>
				<view class="field">
					<view class="title">结束时间:</view>
					<view class="value">{{rentInfo.endDt}}</view>
				</view>
			</view>

			<view class="btn btn-primary btn-pay" @click="open">打开储物柜</view>

			<view class="btn btn-error btn-pay" @click="cancelRent">取消租用</view>

		</view>
	</view>
</template>

<script>

	import util from '@/libs/util.js'
	import DatePicke from "@/components/DatePicke/DatePicke";
	export default {
	    data() {
	        return {
				machineNO: "",
				isLogin: false,
				state: 0,
				teaHouseId: 0,
				selectedTime: "",
				isVipUser: false,
				item: {
					hour: 0
				},
				hourArray:[
					{name: '1', value: '1'},
					{name: '2', value: '2'},
					{name: '3', value: '3'},
					{name: '4', value: '4'},
					{name: '5', value: '5'},
					{name: '6', value: '6'},
					{name: '7', value: '7'},
					{name: '8', value: '8'},
					{name: '9', value: '9'},
					{name: '10', value: '10'},
					{name: '11', value: '11'},
					{name: '12', value: '12'}
				],
				teaConfig: {
					deposit: "",
					vipMoney: "",
					money: "",
					superVipTimes: "",
					subMemberLimit: "",
					lockerPrice: "",
					remark: ""
				},
				rentInfo: {
					"channel":"",
					"endDt":"",
					"machineId":0,
					"remark":"",
					"rockerChannelId":"",
					"startDt":"",
					"userId":""
				}
	        }
	    },
		onLoad(params) {
			if (params.scene) {
				this.machineNO = params.scene;

				if (global.isLogin()) {
					this.isLogin = true;

					if (this.machineNO) {

					} else {
						try {
							let machineNO = uni.getStorageSync('rocker_machineNO');
							if (machineNO) {
								this.machineNO = machineNO;
								uni.removeStorageSync('rocker_machineNO');
							}
						} catch (e) {
							//TODO handle the exception
						}
					}

					if (this.machineNO) {
						this.state = 1;
						this.getConfigInfo();
					}

				} else {
					this.isLogin = false
					//跳转到登录界面
					if (this.machineNO) {
						try {
							uni.setStorageSync('rocker_machineNO',this.machineNO);
						} catch (e) {
							//TODO handle the exception
						}
					}
					this.goPage('/pages/user/auth/auth');
				}
			}
		},
		onShow() {
			// 这部分代码测试时开启
      // this.machineNO = "0116001";
      // this.state = 1;
      // this.getConfigInfo();


      this.selectedTime = this.getNextMonth()
      this.calTime();
			if (global.isLogin()) {
				this.isLogin = true
				this.checkIsVipUser();
			} else {
				this.isLogin = false
			}

			this.getCurrentInfo();
			//this.getConfigInfo();
			//this.selectedTime = this.getCurrentTime();
			//this.getConfigInfo();
		},
		components: {
			DatePicke
		},
		computed: {

		},
	    methods: {
			...util,
			datePicker() {
				if (this.selectedTime=="") {
					this.selectedTime = this.getCurrentTime();
				}

				this.$refs.DatePicker.show();
			},
			checkIsVipUser()  {

				this.$api.post('/user/getInfo', {

				}).then((response) => {
					if (response.ret === 1) {
						if (response.data.level==1||response.data.level==2) {
							this.isVipUser = true;
						} else {
							this.isVipUser = false;
						}
					} else {
						this.$Message.info(response.msg)
					}

				})

			},
			open() {
				this.$api.post('/rocker/open',
				  {
				  }
				).then((response) => {
				console.log(response);
				  if (response.ret===1) {
					this.$Message.success("操作成功")
				  } else {
					this.$Message.error(response.msg)
				  }
				})
			},
			calTime() {
				var currentTime = this.getCurrentTime();
				var startTime = new Date(currentTime.replace(/-/g,'/')).getTime()/1000;
				var endTime = new Date(this.selectedTime.replace(/-/g,'/')).getTime()/1000;
				console.log("startTime");
				console.log(startTime);
				console.log("endTime");
				console.log(endTime);
				console.log(endTime-startTime);
				this.item.hour = Math.ceil((endTime-startTime)/3600);
			},
			getCurrentTime() {
				var now = new Date();
				var year = now.getFullYear(); //得到年份
				var month = now.getMonth()+1;//得到月份
				var date = now.getDate();//得到日期
				var hour= now.getHours();//得到小时数
				var minute= now.getMinutes();//得到分钟数
				var second= now.getSeconds();//得到秒数
				if (month<10) {
					month = "0"+month;
				}
				if (date<10) {
					date = "0"+date;
				}
				if (hour<10) {
					hour = "0"+hour;
				}
				if (minute<10) {
					minute = "0"+minute;
				}
				if (second<10) {
					second = "0"+second;
				}
				var selectedTime = year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
				console.log("what");
				console.log(selectedTime);
				return selectedTime;
			},
      getNextMonth () {
        var now = new Date();
        var year = now.getFullYear(); //得到年份
        var month = now.getMonth()+1;//得到月份
        var date = now.getDate();//得到日期
        var hour= now.getHours();//得到小时数
        var minute= now.getMinutes();//得到分钟数
        var second= now.getSeconds();//得到秒数
        if (month<10) {
          month = "0"+month;
        }
        if (date<10) {
          date = "0"+date;
        }
        if (hour<10) {
          hour = "0"+hour;
        }
        if (minute<10) {
          minute = "0"+minute;
        }
        if (second<10) {
          second = "0"+second;
        }
        let day = date // 获取当前日期的日
        let year2 = year
        let month2 = parseInt(month) + 1
        if (month2 === 13) {
          year2 = parseInt(year2) + 1
          month2 = 1
        }
        let day2 = day
        let days2 = new Date(year2, month2, 0)
        days2 = days2.getDate()
        if (day2 > days2) {
          day2 = days2
        }
        if (month2 < 10) {
          month2 = '0' + month2
        }
        let m = year2 + '-' + month2 + '-' + day2 + " "+hour+":"+minute+":"+second;
        console.log("next month time = " + m)
        return m
      },
			onDateConfirm(e) {
				console.log("回调")
				console.log(e);
				this.selectedTime = e;
				this.calTime();
			},
			getTime(e) {
			   console.log(e)
			},
			bindPickerChange: function(field, arrName, e) {
				let selectItem = this[arrName][e.target.value]
				this.item[field] = selectItem.name
			},
			getTest() {

				this.$api.post('/goodsChannel/getByMachineNO',
				  {
					  machineNO: "100088888"
				  }
				).then((response) => {
				console.log(response);
				  if (response.ret===1) {

				  } else {
					this.$Message.error(response.msg)
				  }
				})
			},
			cancelRent() {
        let page = this;
				uni.showModal({
				    title: '提示',
				    content: '确定取消？',
				    success:  (res) => {
				        if (res.confirm) {

							this.$api.post('/rocker/invalidByUser',
							  {
							  }
							).then((response) => {
							  if (response.ret===1) {
								this.state = 0;
								this.$Message.success("取消成功");
							  } else {
								  if (response.msg=="余额不足") {
								  	this.$Message.error(response.msg);

								  	setTimeout(()=>{
								  		this.goPage("/pages/user/info/vip?teaHouseId="+page.teaHouseId);
								  	},1000);

								  } else {
									 this.$Message.error(response.msg)
								  }
							  }
							})

				        } else if (res.cancel) {
				            //console.log('用户点击取消');
				        }
				    }
				});

			},
			getCurrentInfo() {
				//rocker/getRenting.do
				this.$api.post('/rocker/getRenting',
				  {
				  }
				).then((response) => {
				  if (response.ret===1) {

					if (response.data) {
						this.state = 2;
						this.rentInfo = response.data;
					} else {
						this.state = 0;
					}

				  } else {
					//this.$Message.error(response.msg)
				  }
				})
			},
			scanItem() {
				uni.scanCode({
				    success:  (res) => {
				        //console.log('条码类型：' + res.scanType);
				        //console.log('条码内容：' + res.result);
						if (res.result) {
							this.machineNO = res.result;
							this.state = 1;
							this.getConfigInfo();
						} else {
							this.$Message.error("识别失败");
						}

				    }
				});
			},
			rentItem() {
        let page = this;
        console.log(666666)
        console.log(page.teaHouseId)
				if (this.isVipUser==false) {
					this.$Message.error("当前功能只对会员开放");
					return false;
				}
				if (this.item.hour<=0) {
					this.$Message.error("请选择时间");
					return false;
				}
				this.$api.post('/rocker/rent',
				  {
					machineNO: this.machineNO,
					hours: this.item.hour
				  }
				).then((response) => {
				  if (response.ret===1) {
					 this.getCurrentInfo();
				  } else {
					if (response.msg=="余额不足") {
						this.$Message.error(response.msg);

						setTimeout(()=>{
              this.goPage("/pages/user/info/vip?teaHouseId="+page.teaHouseId);
						},1000);

					} else {
						this.$Message.error(response.msg)
					}
				  }
				})
			},
			toPay(money) {
				wx.login({
					success: (res) => {
						if (res.code) {
							this.wxCode = res.code;

							this.$api.post('/weixin/recharge',
							  {
								code: this.wxCode,
								money: money
							  }
							).then((response) => {
							  if (response.ret===1) {
								//console.log(response);
								let json = "{"+response.data+"}";
								json = json.replace(/'/g,'"');
								json = JSON.parse(json);

								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: json.timeStamp,
									nonceStr: json.nonceStr,
									package: json.package,
									signType: json.signType,
									paySign: json.paySign,
									success:  (res) => {
										//this._cancelOrder();
										//this.$Message.success("支付成功");
										/*
										uni.navigateBack({
											delta: 1
										});
										*/
									},
									fail: function (err) {
										console.log('fail:' + JSON.stringify(err));
									}
								});

							  } else {
								this.$Message.error(response.msg)
							  }
							  this.isCancelSubmit = false;
							});
						}
					}
				});

			},
			getConfigInfo() {
				uni.showLoading({
					title: '加载中'
				});
				this.$api.post('/teaHouseConfig/getByMachineNO',
				  {
					machineNO: this.machineNO
				  }
				).then((response) => {
				  if (response.ret===1) {
					if (response.data) {
					  this.teaConfig = response.data
					  this.teaHouseId = this.teaConfig.teaHouseId;
					  this.teaConfig.deposit = this.teaConfig.deposit/100;
					  this.teaConfig.vipMoney = this.teaConfig.vipMoney/100;
					  this.teaConfig.lockerPrice = this.teaConfig.lockerPrice/100;
					}
				  } else {
					this.$Message.error(response.msg)
				  }
				  uni.hideLoading()
				})
			},
	    }
	}
</script>

<style lang="scss">
	page{
		height: 100%;
	}
	.rocker-qrcode-app{

		.scan-container{

			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			text-align:center;
			margin-top:100upx;
			.image{}
			.text{}
			.btn-scan{
				padding:20upx;
				width:600upx;
				margin-top:50upx;
			}
		}
		.rent{
			.head{
				/*border-bottom:1upx solid #eee;*/
				text-align: center;
				font-weight: bold;
				padding:10upx;
			}
			.btn-pay{
				padding: 20upx;
				width:650upx;
				margin-top:20upx;
				margin-left:20upx;
			}
			.fields{
				border: 1upx solid #eee;

				.field{
					display: flex;
					padding: 20upx;
					.title{
						width:150upx;
            text-align: right;
            padding-right: 20upx;
            font-weight: bold;
					}
					.value{

					}
				}
			}
		}
	}
</style>
